package com.ddh.service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddh.service.domain.player.dto.PlayerDTO;
import com.ddh.service.domain.player.entity.Players;
import com.ddh.service.domain.player.vo.PlayerVO;
import com.ddh.service.enum_.ResultCode;
import com.ddh.service.exception.ServiceException;
import com.ddh.service.mapper.PlayersMapper;
import com.ddh.service.service.PlayersService;
import com.ddh.service.utils.Base64Utils;
import com.ddh.service.utils.JwtUtils;
import com.ddh.service.utils.RSAUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
* @author 11
* @description 针对表【players】的数据库操作Service实现
* @createDate 2025-01-15 16:49:55
*/
@Service
@Slf4j
public class PlayersServiceImpl extends ServiceImpl<PlayersMapper, Players> implements PlayersService {

    //公钥
    private String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUkl9A0ck7nAsHVRxg2aPLLVftOZtBcMNuY+00EnY1DNyycVojqb/en9TP78lAHxMaK1GI0" +
            "slkTKP5SZ8cnAbT4w+DZ16lXPNXFD8LSM2AHVgR8I1w0SHOk8hzafWMtaNvayy/qxaIKxaMLoVYiNh8QNb8ejfuNMl32JlmlSAGiwIDAQAB";

    //私钥
    private String privateKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJSSX0DRyTucCwdVHGDZo8stV+05m0Fww25j7TQSdjUM3LJxWiO" +
            "pv96f1M/vyUAfExorUYjSyWRMo/lJnxycBtPjD4NnXqVc81cUPwtIzYAdWBHwjXDRIc6TyHNp9Yy1o29rLL+rFogrFowuhViI2HxA1vx6N+40yXfYmWaVI" +
            "AaLAgMBAAECgYABc2x6tZHBg0SYTbx5Nabj1Q2Gw4lAmllOOquWVpfQ7M867uByeLXm9qidXzoX5jXJi6LAM07EK/tt88oZ/WwTocfUXzMtez24SpSpU74W3apiR" +
            "suERNaWgD/8fL7UPDiaJFZN85kw2etPiBWe7A23oN3bseB9N0AyBV49KSCYAQJBAOWs792l/QLZM69pyvmmFkj2Ub6F/fr5Qe/SOpTo0NBvUMFbzGFJ0FkblU1B" +
            "sG7Fk27oX9THLmokHu8PdUz/YuMCQQClmbcgTS9ia+zfpuNY/MUgrpLsgwXlBAOBXe1W7Fd5qyywCaKG8VaTg/vsANqh0W/JVmMm94MYez0WPCGJBpY5AkEArU8S7TEs" +
            "u3KEss/kzv9J/6KHSno3jaN64unDNMx9jVsCF/YaQit94U+UGOkBpoTGXMFSVvA6EPPSt9f1TrXDuwJAHV09eK/XGCe1EA+CvtPLjLkH+oJdODfW+0iRfllYRY3R1cFPn" +
            "YgL5wp/UGDyY8FEhjoYSN+Y0m1/7oJpG+gcGQJBANee+dRAcrTSCccet7BHpS+puMOqw7UAuRrRLeKR6givIzckHqJc2zcwG8krOpvDx9x9IhyPbqs0Ozuk+9aCWLU=";

    /**
     * 用户登录具体业务
     * @param playerDTO
     * @return
     */
    @Override
    @SneakyThrows
    public PlayerVO login(PlayerDTO playerDTO) {
        log.info("playerDTO:{}", playerDTO);
        Players players = getOne(new LambdaQueryWrapper<Players>()
                .eq(Players::getUsername, playerDTO.getUsername()));
        if (players == null) {
            throw  new ServiceException(ResultCode.USERNAME_NOT_EXISTS);
        }
        String password = playerDTO.getPassword();
        //密码解密
        //生成数字签名
        String signKey = RSAUtils.sign(Base64Utils.decode(players.getPassword()), privateKey);
        System.out.println("公钥加密后数字签名：" + signKey);
        //校验数字签名
        boolean verify = RSAUtils.verify(Base64Utils.decode(players.getPassword()), publicKey, signKey);
        System.out.println("公钥加密后数字签名校验：" + verify);

        //私钥解密
        System.out.println("私钥解密后字符串：" + new String(RSAUtils.decryptByPrivateKey(Base64Utils.decode(players.getPassword()), privateKey)));

        Integer playerId = players.getPlayerId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("playerId",playerId);
        String token = JwtUtils.generateJwt(map);
        PlayerVO playerVO = new PlayerVO();
        playerVO.setToken(token);
        return playerVO;
    }

    /**
     * 用户注册具体业务
     * @param playerDTO
     * @return
     */
    @Override
    @SneakyThrows
    public Boolean register(PlayerDTO playerDTO) {
        String password=playerDTO.getPassword();
        Players players = getOne(new LambdaQueryWrapper<Players>()
                .eq(Players::getUsername, playerDTO.getUsername()));
        if (players == null) {
            Players players1 = new Players();
            players1.setUsername(playerDTO.getUsername());
            //RSA加密，保证玩家账号安全
            System.out.println("********************公钥加密、生成数字签名、数字签名校验、私钥解密********************");
            System.out.println("原始密码：" + password);
            String encryptPublicPassword = Base64Utils.encode(RSAUtils.encryptByPublicKey(password.getBytes(), publicKey));
            System.out.println("公钥加密后的密码：" + encryptPublicPassword);
            System.out.println("密码加密完成");
            players1.setUsername(playerDTO.getUsername());
            players1.setPassword(encryptPublicPassword);
            return this.save(players1);
        }else {
            //用户名已存在
            throw  new ServiceException(ResultCode.USERNAME_EXISTS);
        }
    }
}
